<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller {
    public function __construct(){
        parent::__construct();
        $this->buser = M('user');
        $user_id = session('user_id');
    }


    public function register(){
        I('get.user_id');
        if(I('get.user_id')){
            session('user_id',null);
        }
        $user = $this->buser->select();
        if(IS_POST){
            $data = array();
            $data = I('post.arr');
            $data['user_pwd'] = md5($data['user_pwd']);
            $res = $this->buser->add($data);
            if($res){
                session('user_id',$res);
                show_msg('添加成功!',U('index.php/index/index'));
            }else{
                show_msg('添加失败！',U('index.php/login/register'));
            }
        }
        $this->display();
    }

    public function login(){
        $verify = new \Think\Verify(); 
        if(IS_POST){
            $data = array();
            $data = I('post.arr');
            // var_dump($data);die;
            $data['pwd'] = md5($data['pwd']);
            $user = $this->buser->where(array('account'=>$data['account']))->find();
            $code_img = I('post.code_img');
            $check = $verify->check($code_img);
            if(!$check){
                $this->success('验证码有误！',U('index.php/login/login'),3);
                exit;
            }
            if(empty($data['account']) || empty($data['account'])){
                $this->success('账号或密码不能为空！',U('index.php/login/login'),3);
                exit;
            }
            if($data['account'] != $user['account'] || $data['pwd'] != $user['pwd']){
                $this->success('账号或密码不正确',U('index.php/login/login'),3);
                exit;
            }else{
                session('user',$user);
                show_msg('登录成功!',U('index.php/index/index'));
            }
        }
        $this->display();
    }

    public function code_img(){
        $config = array(
            'imageW'=>250,
            'imageH'=>50
            );
        $Verify = new \Think\Verify($config);
        $Verify->codeSet = '1234567890';
        $Verify->length = 4;
        $Verify->entry();
    }
}